<template>
  <el-dialog
    v-model="dialogVisible"
    title="导出设置"
    width="400px"
    align-center
    @close="handleClose"
  >
    <div class="export-form">
      <el-form :model="form" label-width="100px">
        <el-form-item label="导出数量：" prop="quantity">
          <el-input
            v-model="form.quantity"
            placeholder="请输入数量"
            @input="validateInput"
            maxlength="4"
          />
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleExport">导出</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, defineProps, defineEmits, watch, onMounted } from 'vue'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  productId: {
    type: [String, Number],
    default: ''
  }
})

const emit = defineEmits(['update:visible', 'export'])

// 对话框可见性，与父组件的visible属性双向绑定
const dialogVisible = ref(props.visible)

// 表单数据
const form = ref({
  quantity: '90' // 默认值
})

// 监听props.visible的变化，更新本地dialogVisible
watch(() => props.visible, (newVal) => {
  dialogVisible.value = newVal
  // 当对话框打开时，加载上次的设置
  if (newVal) {
    loadLastSettings()
  }
})

// 监听本地dialogVisible的变化，通知父组件更新visible
watch(dialogVisible, (newVal) => {
  emit('update:visible', newVal)
})

// 加载上次保存的设置
const loadLastSettings = () => {
  const lastSettings = localStorage.getItem(`qrcode_export_settings_${props.productId}`)
  if (lastSettings) {
    try {
      const settings = JSON.parse(lastSettings)
      form.value.quantity = settings.quantity || '90'
    } catch (e) {
      console.error('Failed to parse last export settings:', e)
    }
  }
}

// 保存当前设置
const saveSettings = () => {
  try {
    localStorage.setItem(
      `qrcode_export_settings_${props.productId}`,
      JSON.stringify({ quantity: form.value.quantity })
    )
    // 同时保存一个全局的最后使用设置，以便在没有产品特定设置时使用
    localStorage.setItem('last_qrcode_export_settings', JSON.stringify({ quantity: form.value.quantity }))
  } catch (e) {
    console.error('Failed to save export settings:', e)
  }
}

// 验证输入，只允许数字且最多4位
const validateInput = (value: string) => {
  // 移除非数字字符
  form.value.quantity = value.replace(/[^\d]/g, '')
  
  // 限制最大长度为4位
  if (form.value.quantity.length > 4) {
    form.value.quantity = form.value.quantity.slice(0, 4)
  }
}

// 处理导出操作
const handleExport = () => {
  // 保存当前设置
  saveSettings()
  
  // 触发导出事件，传递数量参数
  emit('export', {
    productId: props.productId,
    quantity: parseInt(form.value.quantity) || 0
  })
  
  // 关闭对话框
  dialogVisible.value = false
}

// 处理对话框关闭
const handleClose = () => {
  dialogVisible.value = false
}

// 组件挂载时，尝试加载上次的设置
onMounted(() => {
  // 先尝试加载产品特定的设置
  const lastSettings = localStorage.getItem(`qrcode_export_settings_${props.productId}`)
  
  if (lastSettings) {
    try {
      const settings = JSON.parse(lastSettings)
      form.value.quantity = settings.quantity || '90'
    } catch (e) {
      console.error('Failed to parse last export settings:', e)
      
      // 如果产品特定设置加载失败，尝试加载全局设置
      const globalSettings = localStorage.getItem('last_qrcode_export_settings')
      if (globalSettings) {
        try {
          const settings = JSON.parse(globalSettings)
          form.value.quantity = settings.quantity || '90'
        } catch (e) {
          console.error('Failed to parse global export settings:', e)
        }
      }
    }
  } else {
    // 如果没有产品特定设置，尝试加载全局设置
    const globalSettings = localStorage.getItem('last_qrcode_export_settings')
    if (globalSettings) {
      try {
        const settings = JSON.parse(globalSettings)
        form.value.quantity = settings.quantity || '90'
      } catch (e) {
        console.error('Failed to parse global export settings:', e)
      }
    }
  }
})
</script>

<style scoped>
.export-form {
  padding: 20px 0;
}
</style> 